package at.ac.tuwien.dse.health.dashboard;

import at.ac.tuwien.dse.health.dashboard.dto.SurgerySlotDTO;
import at.ac.tuwien.dse.health.entity.Doctor;
import at.ac.tuwien.dse.health.reservation.ReservationCancellation;
import at.ac.tuwien.dse.health.reservation.ReservationRequest;
import at.ac.tuwien.dse.health.security.Secured;
import at.ac.tuwien.dse.health.shared.FilterSettings;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.List;

import static at.ac.tuwien.dse.health.dashboard.HealthService.SurgerySlotMappingFunction;
import static com.google.common.collect.Lists.transform;

/**
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
@Controller
@RequestMapping("/reservation")
public class ReservationController {
	@Inject
	HealthService service;

	@RequestMapping("/request")
	@ResponseBody
	@Secured(Doctor.class)
	public String requestReservation(@RequestParam("patient") int socialSecurityNumber,
									 @RequestParam("maxKilometers") int radius,
									 @RequestParam("surgeryType") String type) {
		ReservationRequest request = service.requestReservation(socialSecurityNumber, radius, type);
		return request != null ? "ok" : null;
	}

	@RequestMapping("/cancel")
	@ResponseBody
	@Secured(Doctor.class)
	public String cancelReservation(@RequestParam("id") int slotId) {
		ReservationCancellation cancellation = service.cancelReservation(slotId);
		return cancellation != null ? "ok" : null;
	}

	@RequestMapping("/types")
	@ResponseBody
	@Secured
	public List<String> getTypes() {
		return service.getDepartmentNames();
	}

	@RequestMapping("/validate")
	@ResponseBody
	@Secured(Doctor.class)
	public String validateSocialSecurityNumber(Integer socialSecurityNumber) {
		return ObjectUtils.toString(service.getPatient(socialSecurityNumber), null);
	}

	@RequestMapping("/slots")
	@ResponseBody
	@Secured
	public List<SurgerySlotDTO> getSurgerySlots(HttpSession session) {
		FilterSettings settings = getFilterSettings(session);
		return transform(service.listSlots(settings), new SurgerySlotMappingFunction());
	}

	FilterSettings getFilterSettings(HttpSession session) {
		FilterSettings settings = session == null ? new FilterSettings()
				: (FilterSettings) session.getAttribute(FilterSettings.SESSION_ATTRIBUTE_NAME);
		if (settings == null) {
			settings = new FilterSettings();
			session.setAttribute(FilterSettings.SESSION_ATTRIBUTE_NAME, settings);
		}
		return settings;
	}
}
